<?php
/*
 * This file is part of EC-CUBE
 *
 * Copyright(c) 2000-2012 LOCKON CO.,LTD. All Rights Reserved.
 *
 * http://www.lockon.co.jp/
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 2
 * of the License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
 */

// {{{ requires
require_once CLASS_EX_REALDIR . 'page_extends/LC_Page_Ex.php';

/**
 * 会員登録のページクラス.
 *
 * @package Page
 * @author LOCKON CO.,LTD.
 * @version $Id: LC_Page_Regist.php 21950 2012-07-02 11:42:51Z pineray $
 */
class LC_Page_Regist extends LC_Page_Ex {

    // {{{ properties

    // }}}
    // {{{ functions
	
	/** POST数据 */
    var $regist_postVal;
    
    /** 新用户注册注册时的插入数据库的key */
    var $arrInsertKey;
    
    /**
     * Page を初期化する.
     *
     * @return void
     */
    function init() {
    	
        parent::init();
        
        
        $this->tpl_mainpage = 'regist/regist.tpl';
        $this->tpl_javascript = '$("#mainBody").removeClass("front");';
        $this->tpl_javascript .= ' $("#mainBody").addClass("not-front page-user-register section-user cron-check-processed");';
    
        //SelectBox 初期化
    	$masterData = new SC_DB_MasterData();
        $this->locationList = $masterData->getMasterData("mst_location");
    	$this->titleList =$masterData->getMasterData("mst_title");
    	$this->degreeList =$masterData->getMasterData("mst_degree");
    	$this->specialtiesList =$masterData->getMasterData("mst_specialties");
    	$this->stateList =$masterData->getMasterData("mst_state");
    	$this->countryList =$masterData->getMasterData("mst_country");
    	
    	//radioBox 初期化
    	$this->maillingAddressList =$masterData->getMasterData("mst_mailling_type");
    	$this->membershipFeeList =$masterData->getMasterData("mst_membership_fee");
    	
    	//是否允许当前页面建立缓存
    	$this->httpCacheControl('private');
    	
    	//引入本页面javascript
    	$this->link_javascript = "js/sapa/regist.js";
    	
    }

    /**
     * Page のプロセス.
     *
     * @return void
     */
    function process() {
        //parent::process();
        $this->action();
        $this->sendResponse();
    }

    /**
     * Page のAction.
     *
     * @return void
     */
    function action() {
        switch ($this->getMode()) {
        	//确认画面
        	case 'confirm':
        		$this->doCheck();
                break;
            //注册    
            case 'regist':
            	$this->doCheck();
            	//插入数据库
            	$objQuery = SC_Query::getSingletonInstance();
            	$objQuery->begin();
            	
        		if($this->regist_postVal['mfee'] == NONE_MEMBER 
        			|| $this->regist_postVal['mfee'] == NONE_MEMBER_STUDENT
        			|| $this->regist_postVal['mfee'] == NONE_MEMBER_CORPORATION){
            		//mst_users
					$objQuery->insert('mst_users', $this->getInsertMstValArray());
					//tab_person_users
					$objQuery->insert('tab_person_users', $this->getInsertTabValArray("mst_users"));
            	}else{
            		//mst_users
					$objQuery->insert('temp_mst_users', $this->getInsertMstValArray());
					//tab_person_users
					$objQuery->insert('temp_tab_person_users', $this->getInsertTabValArray("temp_mst_users"));	
            	}
            	
				
				//插入数据库时 出错了	
				if ($objQuery->isError()) {
					$objQuery->rollback();
					SC_Utils_Ex::sfDispSiteError(FREE_ERROR_MSG, '', true, 'system error please contact the administrator.');
					break;
				}else{
					$objQuery->commit();
				}
				//付费会员付费
				if( $this->regist_postVal['mfee'] != NONE_MEMBER
					&& $this->regist_postVal['mfee'] != NONE_MEMBER_STUDENT
					&& $this->regist_postVal['mfee'] != NONE_MEMBER_CORPORATION){
				
					$_SESSION['regist_userId'] = $this->arrInsertKey[0]['id'];
		       		$payInfo = $this->getPayInfoArr(array(0),array("Membership Fee"),array($this->regist_postVal['mfee']),array(1));
		       		
		       		if($payInfo['result']){
		       			$this->putPayInfoToSession($payInfo['payInfo']);
		       			$this->objSess->SetSession('payMode', 'membershipFee');
		       			SC_Response_Ex::sendRedirect(HTTP_URL."pay/index.php?mode=payInfoConfirm");
		       		}else{
		       							        
				        $this->htmlErrMsg = '<div class="messages error">';
						$this->htmlErrMsg .= '	<ul>';
						$this->htmlErrMsg .= '		<li>';
						$this->htmlErrMsg .= $payInfo['errMsg'];
						$this->htmlErrMsg .= '		</li>'; 
						$this->htmlErrMsg .= '	</ul>';
						$this->htmlErrMsg .= '</div>';
		       		}
		       		SC_Response_Ex::sendRedirect(HTTP_URL.$postVal);
					exit();
				//免费会员注册成功 发送成功mail
				}else {
					//发送注册确认信
	            	$this->sendRegistMail($this->arrInsertKey[0]['id']);
	            	
	            	//转到初期登录完了页面
	            	$this->confirmMail = $this->regist_postVal['mail'];
					$this->tpl_mainpage = 'regist/complete.tpl';
					
					$this->objSess->SetSession(TRANSACTION_ID_NAME, '');
	            	break;	
				}
				
            //从发给邮箱的注册确认链接过来的正式注册	
            case 'userInfoUpdate':
            		$this->getParaFromPost($_POST);
					
            		$tempMstArr = array();
            		$tempMstArr['pass_word'] = $this->regist_postVal['password1'];
            		$tempMstArr['authority_flg'] = $this->regist_postVal['authority'];
		        	$tempMstArr['paymented_date'] =$this->regist_postVal['endDate'];
            		/**
            		//终身会员
					if($this->regist_postVal['mfee'] == "200"){
						$tempMstArr['member_flg'] = '2999-01-01 00:00:00';
					//一般年会员
					}elseif ($this->regist_postVal['mfee'] == "30"){
						$mstRs[0]['paymented_date'] = date("Y-m-d H:i:s",strtotime("+1 year"));
					//学生年会员
					}elseif ($this->regist_postVal['mfee'] == "15"){
						$mstRs[0]['paymented_date'] = date("Y-m-d H:i:s",strtotime("+1 year"));
					}
					**/
            		$tempMstArr['member_flg'] = $this->regist_postVal['mfee'];
            		
            		$tempPersTabUsers = $this->getInsertTabValArray("mst_users");
					unset($tempPersTabUsers['update_time']);
					unset($tempPersTabUsers['create_time']);
					unset($tempPersTabUsers['id']);
					unset($tempPersTabUsers['sex']);
					unset($tempPersTabUsers['del_flg']);
					unset($tempPersTabUsers['membership_fee_id']);
					unset($tempPersTabUsers['img_id']);
					unset($tempPersTabUsers['educational_background']);
					
            		$objQuery = SC_Query::getSingletonInstance();
            		$objQuery->update('mst_users', $tempMstArr,"id = ? ",array($this->getValFromPostOrGet('updateUserId')));
					//tab_person_users
					$objQuery->update('tab_person_users', $tempPersTabUsers,"id = ? ",array($this->getValFromPostOrGet('updateUserId')));
					//$objQuery->commit();
					SC_Response_Ex::sendRedirect(HTTP_URL."mypage/index.php");
                break;
            //--　それ以外のアクセスは無効とする
            default:
                break;
        }
    }

    /**
     * デストラクタ.
     *
     * @return void
     */
    function destroy() {
        parent::destroy();
    }

    
	/**
	 * 验证用户输入的email是否可用
	 * 1，OK的时候返回数组['flg']= 'OK'
	 * 2，NG的时候返回数组['flg']= 'NG'并且返回
	 *    该用户的状态status 和删除flag del_flg
	 */
	function getRegistedMailInfo() {
		
		$mail=$_POST['mail'];
		$mail = strtolower(trim($mail));
		$arrResults = array();
	    $where = '';
	    $arrValues = array($mail);
	        
	    $where .= 'mail_add = ?';
	
	    $objQuery = SC_Query::getSingletonInstance();
	    $rsCount = $objQuery->count('mst_users', $where, $arrValues);
	    
	    if ($rsCount == 0) {
	    	$arrResults['flg']= 'OK';
	    }else{
	    	
	    	$rs = $objQuery->get('status,del_flg ','mst_users', $where, $arrValues);
	    	
	    	$arrResults['flg']= 'NG';
	    	$arrResults['status']= $rs[0]['status'];
	    	$arrResults['del_flg']= $rs[0]['del_flg'];
	    	
	    }
	    return $arrResults;
	}
	/**
	 * 
	 * 画面输入的内容保存在数组里
	 * @param $_POST
	 */
	function getParaFromPost($arrPost){
		
		$this->regist_postVal['mail'] = strtolower(trim($arrPost['mail']));
		$this->regist_postVal['password1'] = $arrPost['password1'];
		
		$this->regist_postVal['location'] = $arrPost['location'];
		$this->regist_postVal['locationVal'] = $this->locationList[$arrPost['location']];
		
		$this->regist_postVal['title'] = $arrPost['title'];
		$this->regist_postVal['titleVal'] = $this->titleList[$arrPost['title']];
		
		$this->regist_postVal['lastname'] = $arrPost['lastname'];
		$this->regist_postVal['firstname'] = $arrPost['firstname'];
		$this->regist_postVal['field_mi'] = $arrPost['field_mi'];
		
		$this->regist_postVal['nameinchinese'] = $arrPost['nameinchinese'];
		$this->regist_postVal['nameinchineseVal'] = $this->degreeList[$arrPost['nameinchinese']];
		
		$this->regist_postVal['affiliation'] = $arrPost['affiliation'];
		
		$this->regist_postVal['specialties'] = $arrPost['specialties'];
		$this->regist_postVal['specialtiesVal'] = $this->specialtiesList[$arrPost['specialties']];
		
		$this->regist_postVal['keywords'] = $arrPost['keywords'];
		
		$this->regist_postVal['mailaddress'] = $arrPost['mailaddress'];
		$this->regist_postVal['mailaddressVal'] = $this->maillingAddressList[$arrPost['mailaddress']];
		
		$this->regist_postVal['street'] = $arrPost['street'];
		$this->regist_postVal['line2'] = $arrPost['line2'];
		$this->regist_postVal['city'] = $arrPost['city'];
		
		$this->regist_postVal['state'] = $arrPost['state'];
		$this->regist_postVal['stateVal'] = $this->stateList[$arrPost['state']];
		
		$this->regist_postVal['zip'] = $arrPost['zip'];
		
		$this->regist_postVal['country'] = $arrPost['country'];
		$this->regist_postVal['countryVal'] = $this->countryList[$arrPost['country']];
		
		$this->regist_postVal['tel'] = $arrPost['tel'];
		$this->regist_postVal['fax'] = $arrPost['fax'];
		
		$this->regist_postVal['mailmagazine'] = $arrPost['mailmagazine'];
		
		if (trim($arrPost['mailmagazine']) == MAILMAGA_AGREE_VALUE) {
			$this->regist_postVal['mailmagazineVal'] = MAILMAGA_AGREE_VALUE;
			$this->regist_postVal['mailmagazine'] = MAILMAGA_AGREE_KEY;
		}elseif (trim($arrPost['mailmagazine']) == MAILMAGA_DISAGREE_VALUE){
			$this->regist_postVal['mailmagazineVal'] = MAILMAGA_DISAGREE_VALUE;
			$this->regist_postVal['mailmagazine'] = MAILMAGA_DISAGREE_KEY;
		}
		$this->regist_postVal['mfee'] = $arrPost['mfee'];
		$this->regist_postVal['mfeeVal'] = $this->membershipFeeList[$arrPost['mfee']];
		
		$this->regist_postVal['authority'] = $arrPost['authority'];
		$this->regist_postVal['endDate'] = $arrPost['endDate'];
	}
	/**
	 * 表mst_users 插入数据编辑
	 * 
	 */
	function getInsertMstValArray(){
		$arrMstUsers = array();
		
		//$arrMstUsers['id']  = $this->regist_postVal['']; 
		$arrMstUsers['user_id'] = $this->regist_postVal['mail']; 
		$arrMstUsers['nick_Name'] = ''; 
		$arrMstUsers['pass_word'] = $this->regist_postVal['password1']; 
		$arrMstUsers['status'] = '2'; //
		$arrMstUsers['authority_flg'] = AUTHORITY_NORMAL;//02:一般 
		$arrMstUsers['member_flg'] = $this->regist_postVal['mfee']; 
		$arrMstUsers['individual_corporate_flg'] = '1';//1,个人 
		$arrMstUsers['paymented_date'] = 'now()'; 
		$arrMstUsers['mail_add'] = $this->regist_postVal['mail']; 
		$arrMstUsers['mailmagazine_flg'] = $this->regist_postVal['mailmagazine']; 
		$arrMstUsers['del_flg'] = '0'; 
		$arrMstUsers['create_time'] =  'now()'; 
		$arrMstUsers['update_time'] =  'now()'; 
		
		return $arrMstUsers;
	}
	/**
	 * 用户注册验证。
	 * 1，已经注册并发送了确认信但没有点连接确认的报错，提示点击重新发送确认信
	 * 2，已经注册并激活了的用户 无法再次注册
	 * 3，被屏蔽，锁定，或者删除的email提示不能注册
	 */
	function  doCheck(){
		
				//-- 电子邮件重复性验证   以及用户状态的验证    该用户 被锁定或者已注册但是没通过验证mail
                // 所以 要抽出来 用户 的状态字段
                $arrRegistMailInfo = $this->getRegistedMailInfo();
                if($arrRegistMailInfo['flg']== 'OK'){
                	$this->getParaFromPost($_POST);
                	//去确认画面
                	$this->tpl_mainpage = 'regist/confirm.tpl';
                }else{
                	$this->tpl_mainpage = 'regist/regist.tpl';
                	//邮箱已经被使用 处理
			    	$accountStatus = $arrRegistMailInfo['status'];
			    	$accountDelete = $arrRegistMailInfo['del_flg'];
			    	
			    	$this->htmlErrMsg  = '<div class="messages error">';
			    	$this->htmlErrMsg .= '<ul>';
			    	
			    	//以用户状态 1:未确认2:已确认3:锁定 4:その他（使用不可）
			    	//注册之后未确认	    	
			    	if($accountStatus == '1'){
			    		$this->htmlErrMsg .= '<li>this account is unidentified please contact the administrator</li>';
			    		//$this->htmlErrMsg .= '<li>if you do not receive the confirmation letter please <a class="pr1" href="#">click here </a>to resend</li>';
			    	}
                	elseif($accountStatus == '3'){
			    		$this->htmlErrMsg .= '<li>Sorry, this email has been locked, please contact the administrator.</li>';
			    	}elseif($accountDelete== "1"){
			    		$this->htmlErrMsg .= '<li>This account was be deleted, please contact the administrator.</li>';
			    	}else{
			    		$this->htmlErrMsg .= '<li>This mailbox unavailable, please contact the administrator.</li>';
			    	}
					$this->htmlErrMsg .= ' </ul>';
					$this->htmlErrMsg .= '</div>'; 
                }
	}
	/**
	 * 向表tab_person_users里的插入数据编辑
	 * 
	 */
	function getInsertTabValArray($tableName){
		$arrTabUsers = array();
		$objQuery = SC_Query::getSingletonInstance();
		$this->arrInsertKey = $objQuery->select('LAST_INSERT_ID() AS id',$tableName);
		
		$arrTabUsers['id']  = $this->arrInsertKey[0]['id']; 
		$arrTabUsers['sex'] = $this->regist_postVal['title']; 
		$arrTabUsers['location_id'] = $this->regist_postVal['location']; 
		$arrTabUsers['title_id'] = $this->regist_postVal['title']; 
		$arrTabUsers['lastname'] = $this->regist_postVal['lastname'];
		$arrTabUsers['firstname'] = $this->regist_postVal['firstname']; 
		$arrTabUsers['middle_name'] = $this->regist_postVal['field_mi']; 
		$arrTabUsers['chinese_name'] = $this->regist_postVal['nameinchinese']; 
		$arrTabUsers['affiliation_employer'] = $this->regist_postVal['affiliation']; 
		$arrTabUsers['specialties_id'] = $this->regist_postVal['specialties']; 
		$arrTabUsers['key_words'] = $this->regist_postVal['keywords']; 	
		$arrTabUsers['mailling_type_id'] = $this->regist_postVal['mailaddress']; 
		$arrTabUsers['street'] = $this->regist_postVal['street'].$this->regist_postVal['line2']; 
		$arrTabUsers['city'] = $this->regist_postVal['city']; 
		$arrTabUsers['State_id'] = $this->regist_postVal['state']; 
		$arrTabUsers['zip_cood'] = $this->regist_postVal['zip']; 
		$arrTabUsers['country_id'] = $this->regist_postVal['country']; 
		$arrTabUsers['tel_no'] = $this->regist_postVal['tel']; 
		$arrTabUsers['fax_no'] = $this->regist_postVal['fax']; 
		$arrTabUsers['membership_fee_id'] = $this->regist_postVal['mfee']; 
		$arrTabUsers['img_id'] = null; 
		$arrTabUsers['educational_background'] = null; 
		$arrTabUsers['del_flg'] = '0'; 
		$arrTabUsers['create_time'] =  'now()'; 
		$arrTabUsers['update_time'] =  'now()';
		
		return $arrTabUsers;
	}
	/**
	 * 发送注册确认信
	 * Enter description here ...
	 */
	/**
	function sendRegistMail() {
		//注册送信
        $objMailText = new SC_SiteView();
        $objMailText->assignobj($this);
        
        //$link= HTTP_URL.'regist/regist.php?mode=mailconfirm&id='.$this->arrInsertKey[0]['id'];
        $link= HTTP_URL.'index.php';
        $name = '';
        if(trim($this->regist_postVal['titleVal']) != '- None -'){
        	$name = $this->regist_postVal['titleVal'].' '.$this->regist_postVal['firstname'];
        }else{
        	$name = $this->regist_postVal['firstname'].' '.$this->regist_postVal['lastname'];
        }
		$objMailText->assign('link', $link);
		$objMailText->assign('name', $name);
		$objMailText->assign('Organization', ORGANIZATION_NAME_SIMPLE);
		
		$objMailText->assign('regist_postVal', $this->regist_postVal);
        $toCustomerMail = $objMailText->fetch("mail_templates/customer_regist_mail.tpl");
        $objMail = new SC_SendMail();
		
        //$this->regist_postVal;
        $objMail->setItem(
                              $this->regist_postVal['mail']	//　宛先
                            , ORGANIZATION_NAME_SIMPLE.' welcome' //　サブジェクト
                            , $toCustomerMail					//　本文
                            , ORGANIZATION_MAIL					//　配送元アドレス
                            , ORGANIZATION_NAME_SIMPLE			//　配送元　名前
                            , ORGANIZATION_MAIL					//　reply_to
                            , ORGANIZATION_MAIL					//　return_path
                            , ORGANIZATION_MAIL					//  Errors_to

                                                            );
        $objMail->setTo($this->regist_postVal['mail'], $name);
        $objMail->sendMail();
    }
	**/
	/**
	 * 用户的验证信里头传过来的用户ID信息验证
	 */
	function getUserMstById($id) {
		$arrResults = array();
	    $where = '';
	    $arrValues = array();
	        
	    $where .= 'id = ? ';
	    $arrValues[] = $id;
	
	    $objQuery = SC_Query::getSingletonInstance();
	    $rsCount = $objQuery->count('mst_users', $where, $arrValues);
	    
	    if ($rsCount != 1 ) {
	    	SC_Utils_Ex::sfDispSiteError(FREE_ERROR_MSG, '', true, 'The url is in error ');
	    }else{
	    	$colArray = array();
	    	$colArray[] = "status";
	    	$colArray = "del_flg";
	    	
	    	$rs = $objQuery->select('status,del_flg ,update_time','mst_users', $where, $arrValues);
	    	//用户状态不对
	    	if($rs[0]['status'] != '1' || $rs[0]['del_flg'] != '0'){ 
	    		$arrResults['flg']= 'NG';
	    		$this->htmlErrMsg  = '<div class="messages error">';
		    	$this->htmlErrMsg .= '<ul>';
	    		$this->htmlErrMsg .= '<li>the regist data is in error please do regist  againe</li>';
				$this->htmlErrMsg .= ' </ul>';
				$this->htmlErrMsg .= '</div>'; 
	    	}else{
	    			
	    			$registTime = $rs[0]['update_time'];
	    			$now = new DateTime();
	    			//发送了确认信到现在的时间
	    			$intervalHour = ($now-$registTime)/ 3600;
	    			
	    			//link 失效
	    			if ($intervalHour >=48){
	    				$arrResults['flg']= 'NG';
	    				
	    				$this->htmlErrMsg  = '<div class="messages error">';
				    	$this->htmlErrMsg .= '<ul>';
			    		$this->htmlErrMsg .= '<li>We are already send confirm mail to this email yet </li>';
			    		$this->htmlErrMsg .= '<li>但是在您注册后的48 个小时内我们没有得到您的确认。  </li>';
			    		$this->htmlErrMsg .= '<li>please <a class="pr1" href="#">click here </a>to send the mail againe</li>';
						$this->htmlErrMsg .= ' </ul>';
						$this->htmlErrMsg .= '</div>'; 
	    			}else{
	    				$arrResults['flg']= 'OK';
	    			}
	    	}
	    	
	    }
	    return $arrResults;
	}
	
	/**
	 * 注册成功发送邮件
	 * Enter description here ...
	 * @param unknown_type $userDate 用户数据
	 */
    function sendRegistSuccessMail(){
    	//注册成功发送邮件
        $objMailText = new SC_SiteView();
        $objMailText->assignobj($this);
	    
        $name = '';
        //有称呼
        if($this->objSess->GetSession('title') != '- None -'){
        	$name = $this->objSess->GetSession('title') .' '.$this->objSess->GetSession('lastname');
        }else{
        	$name =  $this->objSess->GetSession('firstname').' '. $this->objSess->GetSession('lastname');
        }
		$objMailText->assign('name', $name);
        $toCustomerMail = $objMailText->fetch("mail_templates/regist_complete_mail.tpl");
        $objMail = new SC_SendMail();
		
        //$this->regist_postVal;
        $objMail->setItem(
                             $this->objSess->GetSession('user_email')	//　宛先
                            , 'Welcome you be a '.ORGANIZATION_NAME_SIMPLE.' member' //　サブジェクト
                            , $toCustomerMail					//　本文
                            , ORGANIZATION_MAIL					//　配送元アドレス
                            , ORGANIZATION_NAME_SIMPLE			//　配送元　名前
                            , ORGANIZATION_MAIL					//　reply_to
                            , ORGANIZATION_MAIL					//　return_path
                            , ORGANIZATION_MAIL					//  Errors_to

                                                            );
        $objMail->setTo($this->objSess->GetSession('user_email'), $name);
        $objMail->sendMail();
    }
}